package com.sendpo.zjx.sendpo.activity;

import android.content.Context;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.github.czy1121.view.CornerLabelView;
import com.google.gson.Gson;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.jingchen.pulltorefresh.PullableRecyclerView;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.domain.MerchandiseDomain;
import com.sendpo.zjx.sendpo.domain.MerchandiseStoreDomain;
import com.sendpo.zjx.sendpo.domain.StoreDomain;
import com.sendpo.zjx.sendpo.net.HttpCode;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.services.AmapLocationService;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by 朱俊鑫 on 2018
 */

public class DownMerchandiseActivity extends AppCompatActivity {


    @BindView(R.id.backbt)
    RelativeLayout backbt;
    @BindView(R.id.head)
    RelativeLayout head;
    @BindView(R.id.recyclerview)
    PullableRecyclerView recyclerview;
    @BindView(R.id.pulltofresh)
    PullToRefreshLayout pulltofresh;
    private int pagenow = 1;
    private RecylcerAdaper adpter;
    private LinearLayoutManager lm;
    private int merchantsId=0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_downmerchandise);
        ButterKnife.bind(this);
        Tools.initStatus(this, R.color.black);
        merchantsId=getIntent().getIntExtra("merchantsId",0);
        initComponent();
    }

    private void initComponent() {
        lm = new LinearLayoutManager(this, OrientationHelper.VERTICAL, false);
        recyclerview.setLayoutManager(lm);
        List<MerchandiseStoreDomain.DataBean> data=new ArrayList<>();
        recyclerview.setAdapter(adpter=new RecylcerAdaper(data,this));
        pulltofresh.setOnPullListener(new PullToRefreshLayout.OnPullListener() {
            @Override
            public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
                pagenow=1;
                query(pagenow);

            }

            @Override
            public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
                pagenow++;
                append(pagenow);
            }
        });
        pulltofresh.autoRefresh();

    }


    @OnClick(value = {R.id.backbt})
    public void onMyClick(View view){
         switch (view.getId()){
             case R.id.backbt:
                    finish();
                 break;
         }
    }

    public class RecylcerAdaper extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        public List<MerchandiseStoreDomain.DataBean> dataBeen;
        public LayoutInflater inflater;
        public RecylcerAdaper(List<MerchandiseStoreDomain.DataBean> dataBeen, Context context) {
            inflater = LayoutInflater.from(context);
            this.dataBeen = dataBeen;
        }
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            RecyclerView.ViewHolder ih = null;
            ih = new IndexHoler(inflater.inflate(R.layout.layout_generic_store_listitem, parent, false));
            return ih;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            final IndexHoler ih = (IndexHoler) holder;
            final MerchandiseStoreDomain.DataBean dataBean = dataBeen.get(position);
            ih.shopping_title_user.setText("" + dataBean.getMerchandiseName());
            ih.shopping_info_user.setText("");
            Glide.with(DownMerchandiseActivity.this)
                    .load("" + dataBean.getMerchandiseHeadimg())
                    .asBitmap()
                    .animate(R.anim.fade_in)
                    .override(500, 500)
                    .into(ih.icon);
            ih.now_tv.setText("¥" + dataBean.getMerchandiseCurrentprice());
            ih.origin_tv.setText("¥" + dataBean.getMerchandiseOriginalprice());
            ih.rootView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("merchandiseId", dataBean.getMerchandiseId());
                    Tools.redirectActivity(DownMerchandiseActivity.this, GeneicStoreInfoActivity.class, map);
                }
            });

            ih.labelview.setText1("");
            ih.labelview.setVisibility(View.GONE);
            ih.down_bt.setVisibility(View.VISIBLE);
            ih.down_bt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    down(dataBean.getMerchandiseId()+"",position);
                }
            });
        }

        @Override
        public int getItemCount() {
            return dataBeen.size();
        }

        public class IndexHoler extends RecyclerView.ViewHolder {
            public View rootView;
            public ImageView icon;
            public TextView origin_tv;
            public TextView shopping_title_user;
            public TextView shopping_info_user;
            public TextView now_tv;
            public TextView song_tv;
            public TextView xiandao_tv;
            public CornerLabelView labelview;
           public Button down_bt;
            public IndexHoler(View itemView) {
                super(itemView);
                down_bt=itemView.findViewById(R.id.down_bt);
                labelview = itemView.findViewById(R.id.labelview);
                song_tv = itemView.findViewById(R.id.song_tv);
                now_tv = itemView.findViewById(R.id.now_tv);
                xiandao_tv = itemView.findViewById(R.id.xiandao_tv);
                rootView = itemView;
                icon = itemView.findViewById(R.id.icon);
                origin_tv = itemView.findViewById(R.id.origin_tv);
                origin_tv.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);//下划线
                origin_tv.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); //中间横线
                origin_tv.getPaint().setAntiAlias(true);// 抗锯齿
                origin_tv.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);  // 设置中划线并加清晰
                shopping_title_user = itemView.findViewById(R.id.shopping_title_user);
                shopping_info_user = itemView.findViewById(R.id.shopping_info_user);
            }
        }

        public void deleteRow(int position) {
            dataBeen.remove(position);
            notifyDataSetChanged();
        }

        public void initRefresh(List<MerchandiseStoreDomain.DataBean> domains) {
            this.dataBeen.removeAll(this.dataBeen);
            this.dataBeen.addAll(domains);
            notifyDataSetChanged();
        }

        public void initAppend(List<MerchandiseStoreDomain.DataBean> domains) {
            this.dataBeen.addAll(domains);
            notifyDataSetChanged();
        }

        public void delete(int position) {
            this.dataBeen.remove(position);
            notifyDataSetChanged();
        }
        public void  down(String merchandiseId, final int position){
             Map<String,String> map=new HashMap<>();
             map.put("merchandiseId",merchandiseId);
             Xutils.POST(HttpUrl.merchandisedown, map, new Callback.CommonCallback<String>() {
                 @Override
                 public void onSuccess(String result) {
                     System.out.println("*********************result"+result);
                     try {
                         JSONObject jsonObject=new JSONObject(result);
                         Toast.makeText(getApplicationContext(),jsonObject.getString("message"),Toast.LENGTH_SHORT).show();
                     System.out.println("*********************");
                         switch (jsonObject.getInt("state")){
                         case HttpCode.SUCCESS:
                             delete(position);
                             break;
                        }
                     } catch (JSONException e) {
                         e.printStackTrace();
                     }
                 }

                 @Override
                 public void onError(Throwable ex, boolean isOnCallback) {
                     Toast.makeText(getApplicationContext(),"请稍后再试",Toast.LENGTH_SHORT).show();
                 }

                 @Override
                 public void onCancelled(CancelledException cex) {

                 }

                 @Override
                 public void onFinished() {

                 }
             });
        }

    }


    public void query(int pagenow){
            Map<String,String> map=new HashMap<>();
             map.put("pagenow",pagenow+"");
             map.put("merchantsId",merchantsId + "");
             Xutils.POST(HttpUrl.merchandisebymerchantidfenye, map, new Callback.CommonCallback<String>() {
                 @Override
                 public void onSuccess(String result) {
                      pulltofresh.refreshFinish(PullToRefreshLayout.SUCCEED);
                      Gson gson=new Gson();
                  MerchandiseStoreDomain domain=gson.fromJson(result,MerchandiseStoreDomain.class);
                   if(adpter==null){
                     recyclerview.setAdapter(adpter=new RecylcerAdaper(domain.getData(),DownMerchandiseActivity.this));
                   }else{
                       adpter.initRefresh(domain.getData());
                   }
                 }

                 @Override
                 public void onError(Throwable ex, boolean isOnCallback) {
                     pulltofresh.refreshFinish(PullToRefreshLayout.FAIL);
                 }

                 @Override
                 public void onCancelled(CancelledException cex) {

                 }

                 @Override
                 public void onFinished() {

                 }
             });
    }

    public void append(int pagenow){
        Map<String,String> map=new HashMap<>();
        map.put("pagenow",pagenow+"");
        map.put("merchantsId",merchantsId + "");
        Xutils.POST(HttpUrl.merchandisebymerchantidfenye, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                pulltofresh.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                Gson gson=new Gson();
                MerchandiseStoreDomain domain=gson.fromJson(result,MerchandiseStoreDomain.class);
                if(adpter==null){
                    recyclerview.setAdapter(adpter=new RecylcerAdaper(domain.getData(),DownMerchandiseActivity.this));
                }else{
                    adpter.initAppend(domain.getData());
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                pulltofresh.loadmoreFinish(PullToRefreshLayout.FAIL);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }




}
